const express = require('express');
const app = express();
const port = 8080;
const fs = require('fs');
const { createProxyMiddleware } = require('http-proxy-middleware');
const config = require('./proxy.config.js');
const NotFoundHTML = fs.readFileSync('./404.html');

// app.use(express.json()); // 解析 JSON 请求体 ps：不可在此解析json数据，否则对象数据是发不出去的/*  */


app.all('*', async (req, res) =>{
  if (isRightPath(req.url,res)) { //判断请求路径是否正确 
    console.log(req.body);
    // 转发请求
    let proxy = createProxyMiddleware(config.serve.Proxy['/api']);

    proxy(req,res)

    return;
    
  }else
      //如果路径拼写不对或无该页面资源
  { 
    res.statusCode = 404;
    res.setHeader('Content-Type', 'text/html;charset=utf-8');
    res.send(NotFoundHTML)
  }
}) 

// 判断请求路径是否正确 
const isRightPath = ( path )=>{
  const pathList = path.split('/')
  // console.log(pathList);
  if (pathList[1] == 'api') {

    if (pathList[2] == 'users') {
      return true
    } else {
      return false
    }

    
  }else{
    return false
  }
}
// 监听端口
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});